// src/utils/http.ts
import { useMemberStore } from "../store/modules/member"
// 请求基地址
// const baseURL = 'https://www.diandianyouke.cn:8081'
// const baseURL = 'https://www.diandianyouke.cn:8081'
const baseURL = 'https://www.diandianyouke.cn:8081'
const memberStore = useMemberStore()
// 拦截器配置
const httpInterceptor = {
  // 拦截前触发
  invoke(options) {
    // 1. 非 http 开头需拼接地址
    if (!options.url.startsWith('http')) {
      options.url = baseURL + options.url
    }
    // 2. 请求超时
    if (!options.timeout) {
      options.timeout = 10000
    }
    // 3. 添加小程序端请求头标识
    options.header = {
      'Content-Type': 'application/x-www-form-urlencoded',
      ...options.header,
    }
    // 4. 添加 token 请求头标识
    const token = uni.getStorageSync('token')
    if (token) {
      options.header.token = token
    }
  },
}
// 封装网络请求函数
export function httpRequest(url, method, data,time) {
  return new Promise((resolve, reject) => {
    // uni.showLoading({
    //   title: '加载中',
    //   mask: false
    // })
    const requert = {
      url: baseURL + url,
      method: method,
      data: data,
      success: (res) => {
        // 请求成功
        // uni.hideLoading()
        resolve(res.data);
        if (res.data.code == '4012') {
          uni.showToast({
            title: '身份过期请重新登录',
            icon: 'none',
          })
          uni.removeStorageSync('token')
          setTimeout(() => {
            uni.switchTab({ url: '/pages/index/index' })
          }, 1500);
        }
      },
      fail: (error) => {
        // uni.hideLoading()
        // 请求失败
        uni.hideLoading()
        uni.showToast({
          title: '请检查网络后重试',
          icon: 'none'
        })
        reject(error);
      }
    }
    if(time){
      requert.timeout = time
    }
    uni.request(requert);
  });
}
export function httpRequestFile(url, method, data,time) {
  const token = uni.getStorageSync('token')
  return new Promise((resolve, reject) => {
    uni.request({
      url: baseURL + url,
      method: method,
      data: data,
      header: {
        'Content-Type': 'multipart/form-data',
        'Content-Length': '2000000000',
        'token': token
      },
      success: (res) => {
        // 请求成功
        resolve(res.data);
      },
      fail: (error) => {
        // 请求失败
        reject(error);
      }
    });
  });
}

// 拦截 request 请求
uni.addInterceptor('request', httpInterceptor)